var express = require('express');
var router = express.Router();
var Goodslist = require("../models/goodslist");
var Norms = require("../models/norms");

var multer  = require('multer');
var upload = multer({ dest: 'upload/' })
var shangchuan = require('../models/uplodaTengxun_cos.js');

//获取商品数据
router.get('/getGoods', function(req, res, next) {
    let page = parseInt(req.param("page"));
    let pageSize = parseInt(req.param("pageSize"));
    // let sort = req.param("sort");
    let skip = (page-1)*pageSize;
    let params = {};

    if (req.param("type") != ""){
        params.type=req.param("type")
    }
    if (req.param("shelves") != ""){
        params.shelves=req.param("shelves")
    }
    if (req.param("goodName") != ""){
        params.goodName={$regex: req.param("goodName")}
    }
        // console.log(params)
    let model = Goodslist.find(params).skip(skip).limit(pageSize);
    // goodsModel.sort({"salePrice" : sort});
    //var model = Goodslist.find();
    Goodslist.count(params, (err, count) => {
        if(err){
            res.json({
                status:"1",
                msg:err
            })
        }else {
            model.exec(function (err1, result) {
                if (err1) {
                    res.json({
                        status: "1",
                        msg: err,
                    })
                } else {
                    res.json({
                        status: "0",
                        msg: "",
                        result: {
                            count: count,
                            list: result
                        }
                    })
                }
            });
        }
    });
});

//添加good
var cpUpload = upload.fields([{ name: 'goodsfiles', maxCount: 9 }, { name: 'mainfiles', maxCount: 9 }]);
router.post('/addGoods', cpUpload, async function (req, res, next) {
    console.log(req.files['goodsfiles']);
    console.log(req.body);

    let param = {
            goodName : req.body.name,
            shelves : true,
            type : req.body.resource,
            goodsfiles : [],
            mainfiles:[],
            title : "",
            salePrice : req.body.salePrice,
            costPrice : req.body.costPrice,
            norms: [],
            choosesize:req.body.choosesize
        };

    for(let q=0;q<req.files['goodsfiles'].length;q++){
        let goodsfiles=[];
            goodsfiles[q] =  await shangchuan(req.files["goodsfiles"][q]);
            param["goodsfiles"] = goodsfiles;
    }
    for(let i=0;i<req.files['mainfiles'].length;i++){
        let mainfiles=[];
            mainfiles[i] =  await shangchuan(req.files["mainfiles"][i]);
            param["mainfiles"] = mainfiles;
    }

    req.body.choosesize.forEach((val,ind)=>{
        param.norms[ind]={val:req.body[val].split(",")}
    });

    // let param = {
    //     shelves : true,
    //     salse: 0,
    // };
    // if(req.body.name != ''){
    //     param["goodName"] = req.body.name
    // }
    // if(req.body.type != ''){
    //     param["type"] = req.body.resource
    // }
    // if(req.body.salePrice != ''){
    //     param["salePrice"] = req.body.salePrice
    // }
    // if(req.body.costPrice != ''){
    //     param["costPrice"] = req.body.costPrice
    // }
    // if(req.body.choosesize != ''){
    //
    //     let choosesize = [];
    //     // console.log(typeof(req.body.choosesize));
    //     if(typeof(req.body.choosesize) == "string"){
    //         choosesize[0] = req.body.choosesize;
    //     }else {
    //         choosesize = req.body.choosesize;
    //     }
    //     param["choosesize"] = choosesize;
    //     let norms= [];
    //     choosesize.forEach((val,ind)=>{
    //         // console.log(req.body[val])
    //         norms[ind]={val:req.body[val].split(",")}
    //     });
    //     param["norms"] = norms;
    // }
    // if(req.files['goodsfiles'] != undefined){
    //     let goodsfiles = [];
    //     for(let q=0;q<req.files['goodsfiles'].length;q++){
    //
    //         // goodsfiles[q] =  "http://localhost:3000/typelist/" + req.files["goodsfiles"][q].path;
    //         goodsfiles[q] =  await shangchuan(req.files["goodsfiles"][q]);
    //     }
    //     param["goodsfiles"] = goodsfiles;
    //
    // }
    // if(req.files['mainfiles'] != undefined ){
    //     let mainfiles = [];
    //     for(let i=0;i<req.files['mainfiles'].length;i++){
    //         mainfiles[i] =  await shangchuan(req.files["mainfiles"][i]);
    //         //mainfiles[i] =  "http://localhost:3000/typelist/" + req.files["mainfiles"][i].path;
    //     }
    //     param["mainfiles"] = mainfiles;
    // }

    Goodslist.create( param ,function(err,doc){
        if(err){
            res.json({
                status:"1",
                msg:err,
                result: ""
            })
        }else{
            if(doc){
                res.json({
                    status:"0",
                    msg:"添加成功",
                    result: "suc"
                })
            }
        }
    })
})

//修改good
//var cpUpload = upload.fields([{ name: 'goodsfiles', maxCount: 3 }, { name: 'mainfiles', maxCount: 3 }]);
router.post('/editGoods', cpUpload, async function (req, res, next) {
    // console.log(req.body)
    // console.log(req.files)

    let param = {};
    if(req.body.name != ''){
        param["goodName"] = req.body.name
    }
    if(req.body.type != ''){
        param["type"] = req.body.resource
    }
    if(req.body.salePrice != ''){
        param["salePrice"] = req.body.salePrice
    }
    if(req.body.costPrice != ''){
        param["costPrice"] = req.body.costPrice
    }
    if(req.body.choosesize != ''){
        // param["choosesize"] = req.body.choosesize;
        // let norms= [];
        // req.body.choosesize.forEach((val,ind)=>{
        //
        //     norms[ind]={val:req.body[val].split(",")}
        // });
        // param["norms"] = norms;
        let choosesize = [];
        // console.log(req.body.choosesize);
        // console.log(req.body)
        //
        // console.log(typeof(req.body.choosesize));
        if(typeof(req.body.choosesize) == "string"){
            choosesize[0] = req.body.choosesize;
        }else {
            choosesize = req.body.choosesize;
        }
        param["choosesize"] = choosesize;
        let norms= [];
        choosesize.forEach((val,ind)=>{
            // console.log(req.body[val])
            norms[ind]={val:req.body[val].split(",")}
        });
        param["norms"] = norms;
    }
    if(req.files['goodsfiles'] != undefined){
        let goodsfiles = [];
        for(let q=0;q<req.files['goodsfiles'].length;q++){
            goodsfiles[q] =  await shangchuan(req.files["goodsfiles"][q]);
        }
        param["goodsfiles"] = goodsfiles;

    }
    if(req.files['mainfiles'] != undefined ){
        let mainfiles = [];
        for(let i=0;i<req.files['mainfiles'].length;i++){
            mainfiles[i] =  await shangchuan(req.files["mainfiles"][i]);
        }
        param["mainfiles"] = mainfiles;
    }

    // console.log(param)

    Goodslist.update({
        _id:req.body.id
    },{
        $set:param
    },function(err,doc){
        if(err){
            res.json({
                status:"1",
                msg:err,
                result: ""
            })
        }else{
            if(doc){
                res.json({
                    status:"0",
                    msg:"修改成功",
                    result: "suc"
                })
            }
        }
    });

    // let param = {
    //     goodName : req.body.name,
    //     shelves : true,
    //     type : req.body.resource,
    //     goodsfiles : [],
    //     mainfiles:[],
    //     title : "",
    //     salePrice : req.body.salePrice,
    //     costPrice : req.body.costPrice,
    //     norms: [],
    //     choosesize:req.body.choosesize
    // };
    // for(let q=0;q<req.files['goodsfiles'].length;q++){
    //     param.goodsfiles[q] =  "http://localhost:3000/typelist/" + req.files["goodsfiles"][q].path;
    // }
    // for(let i=0;i<req.files['mainfiles'].length;i++){
    //     param.mainfiles[i] =  "http://localhost:3000/typelist/" + req.files["mainfiles"][i].path;
    // }
    //
    // req.body.choosesize.forEach((val,ind)=>{
    //    console.log(req.body[val])
    //     param.norms[ind]={val:req.body[val].split(",")}
    // });
    //
    // Goodslist.update({
    //     _id:req.body.id
    // },{
    //     $set:{
    //         "goodName" : param.goodName,
    //         "shelves" : true,
    //         "type" : param.type,
    //         "goodsfiles" : param.goodsfiles,
    //         "mainfiles":param.mainfiles,
    //         "title" : "",
    //         "salePrice" : param.salePrice,
    //         "costPrice" : param.costPrice,
    //         "norms" :param.norms,
    //         "choosesize":param.choosesize,
    //     }
    // },function(err,doc){
    //     if(err){
    //         res.json({
    //             status:"1",
    //             msg:err
    //             result: ""
    //         })
    //     }else{
    //         if(doc){
    //             res.json({
    //                 status:"0",
    //                 msg:"修改成功",
    //                 result: "suc"
    //             })
    //         }
    //     }
    // });
})


// 修改上下架
router.post('/editShelves', function(req, res, next) {
    let page = parseInt( req.body.page);
    let pageSize = parseInt( req.body.pageSize);
    // let sort = req.param("sort");
    let skip = (page-1)*pageSize;
    let params = {};

    if (req.body.type != ""){
        params = {
            type: req.body.type
        }
    }

    let model = Goodslist.find(params).skip(skip).limit(pageSize);

    model.update( {"_id": req.body.shelves },{"$set":{"shelves":req.body.isShelves}},{ multi: true },function(err,doc){
        if(err){
            res.json({
                status:"1",
                msg:err,
                result: ""
            })
        }else{
            if(doc){
                res.json({
                    status:"0",
                    msg:"修改成功",
                    result: "suc"
                })
            }
        }
    })
});

// //查找商品
// router.post('/getOneGoods', function(req, res, next) {
//    // / let model = Goodslist.find({"shelves": true, $or:[{"goodName":{$regex: req.param("goodsName")}}]}).skip(skip).limit(pageSize).sort(pri);
//
//     Goodslist.find({ //查找一条
//
//     },(err, doc)=>{
//         if(err){
//             res.json({
//                 status:"1",
//                 msg:err,
//             })
//         }else{
//             res.json({
//                 status:"0",
//                 msg:"",
//                 result:{
//                     list:doc
//                 }
//             })
//         }
//     })
// });

//获取上架商品数据
router.get('/getShelvesGoods', function(req, res, next) {
    let page = parseInt(req.param("page"));
    let pageSize = parseInt(req.param("pageSize"));
    // let sort = req.param("sort");
    let skip = (page-1)*pageSize;
    let params = { shelves:true};

    let model = Goodslist.find(params).skip(skip).limit(pageSize);
    // goodsModel.sort({"salePrice" : sort});
    //var model = Goodslist.find();
    Goodslist.count(params, (err, count) => {
        if(err){
            res.json({
                status:"1",
                msg:err,
            })
        }else {
            model.exec(function (err1, result) {
                if (err1) {
                    res.json({
                        status: "1",
                        msg: err,
                    })
                } else {
                    res.json({
                        status: "0",
                        msg: "",
                        result: {
                            count: count,
                            list: result
                        }
                    })
                }
            });
        }
    });
});

//查找上架商品
router.post('/getOneShelvesGoods', function(req, res, next) {

    Goodslist.find({
        "shelves": true, $or:[{"goodName":{$regex: req.body.goodName}}]
    },(err, doc)=>{
        if(err){
            res.json({
                status:"1",
                msg:err,
            })
        }else{
            res.json({
                status:"0",
                msg:"",
                result:{
                    list:doc
                }
            })
        }
    })
});

//删除商品
router.post('/delGoods', function(req, res, next) {

     Goodslist.remove({"_id":req.body.id}, function (err,doc){
        if(err){
            res.json({
                status:"1",
                msg:err,
                result: ""
            })
        }else{
            if(doc){
                res.json({
                    status:"0",
                    msg:"删除成功",
                    result: "suc"
                })
            }
        }
    });
});

//批量删除
router.post('/delmoreGoods', function(req, res, next) {
    Goodslist.remove({ _id: { $in: req.body.shelves } }, function (err,doc){
        if(err){
            res.json({
                status:"1",
                msg:err,
                result: ""
            })
        }else{
            if(doc){
                res.json({
                    status:"0",
                    msg:"删除成功",
                    result: "suc"
                })
            }
        }
    });
})

//获取类型数据
router.get('/getNorms', function(req, res, next) {
    var model = Norms.find();
    model.exec(function(err,result){
        if(err){
            res.json({
                status:"1",
                msg:err,
            })
        }else{
            res.json({
                status:"0",
                msg:"",
                result:{
                    count:result.length,
                    list:result
                }
            })
        }
    });
});

//修改类型
// router.post('/editNorms', function(req, res, next) {
//     console.log(req.body.size)
//     console.log(req.body.color)
//     var param = { },editparam ={};
//     if(req.body.size != undefined){
//         param.size = req.body.size
//     }else if(req.body.color != undefined){
//         param.color = req.body.color
//     }
//     console.log(param)
//     Typelist.update({
//         _id:param.id
//     },{
//         $set:{'typePic':param.typePic,"type":param.type}
//     },function(err,doc){
//         if(err){
//             res.json({
//                 status:"1",
//                 msg:err
//                 result: ""
//             })
//         }else{
//             if(doc){
//                 res.json({
//                     status:"0",
//                     msg:"修改成功",
//                     result: "suc"
//                 })
//             }
//         }
//     });
// });

//添加尺寸数据
router.post('/addNorms', function(req, res, next) {

    Norms.findOne({id:"1000"},function(err ,normsDOC){
        if(err){
            res.json({
                status:"1",
                msg:err,
            })
        }else {

            if(req.body.size != undefined){
                if(normsDOC.size.indexOf(req.body.size)<0){
                    normsDOC.size.push(req.body.size)

                    normsDOC.save(function(err2,doc2){
                        if(err2){
                            res.json({
                                status:"1",
                                msg:err2,
                            })
                        }else {
                            res.json({
                                status:"0",
                                msg:"",
                                result:"添加成功"
                            })
                        }
                    })
                }else {
                    res.json({
                        status:"1",
                        msg:"",
                        result:"尺寸已存在"
                    })
                }
            }else if(req.body.color != undefined){
                if(normsDOC.color.indexOf(req.body.color) < 0){
                    normsDOC.color.push(req.body.color)

                    normsDOC.save(function(err2,doc2){
                        if(err2){
                            res.json({
                                status:"1",
                                msg:err2,
                            })
                        }else {
                            res.json({
                                status:"0",
                                msg:"",
                                result:"添加成功"
                            })
                        }
                    })
                }else {
                    res.json({
                        status:"1",
                        msg:"",
                        result:"颜色已存在"
                    })
                }
            }


        }
    })
});

module.exports = router;